package com.innovation.ic.sc.web.controller.sc;

import com.innovation.ic.b1b.framework.util.IpAddressUtil;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.sc.base.model.sc.User;
import com.innovation.ic.sc.base.pojo.constant.HttpHeader;
import com.innovation.ic.sc.base.pojo.constant.LoginConstants;
import com.innovation.ic.sc.base.pojo.constant.UserType;
import com.innovation.ic.sc.base.pojo.variable.*;
import com.innovation.ic.sc.base.vo.UsersVo;
import com.innovation.ic.sc.web.controller.AbstractController;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * 账号API
 */
@Api(value = "账号API", tags = "UserController")
@RestController
@RequestMapping("/api/v1/user")
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    /**
     * 通过账号密码登录
     *
     * @return 返回登录用户信息
     */
    @HystrixCommand
    @ApiOperation(value = "通过账号密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "登入账户", dataType = "String", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", required = true)
    })
    @RequestMapping(value = "/loginByUsername", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<AuthenticationUser>> loginByUsername(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!StringUtils.validateParameter(usersVo.getUserName()) || !StringUtils.validateParameter(usersVo.getPassword())) {
            String message = "调用接口【/api/v1/user/loginByUsername时，参数userName与password不能为空";
            log.warn(message);
            ApiResult<AuthenticationUser> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        //通过feign 传递账号密码 去第三方获取 token
        ServiceResult<AuthenticationUser> serviceResult = userService.findUser(usersVo);
        if (serviceResult.getResult() == null) {
            ApiResult<AuthenticationUser> apiResult = new ApiResult<>();
            apiResult.setSuccess(serviceResult.getSuccess());
            apiResult.setCode(HttpStatus.UNAUTHORIZED.value());
            apiResult.setMessage(serviceResult.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }

        // 将用户信息存储到redis中
        this.setAuthenticationUser(serviceResult.getResult());

        // 判断用户id是否返回
        if (!StringUtils.isEmpty(serviceResult.getResult().getId())) {
            //将账号信息存入登录日志表中
            String ipAddress = IpAddressUtil.getIpAddress(request);
            userLoginLogService.addUserLog(serviceResult.getResult().getUsername(), ipAddress, LoginConstants.ACCOUNT_PASSWORD_LOGIN);
        }

        ApiResult<AuthenticationUser> apiResult = new ApiResult<>();
        apiResult.setSuccess(serviceResult.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(serviceResult.getMessage());
        apiResult.setResult(serviceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 通过账号查询手机号(此接口前端已经废弃)
     *
     * @return 返回手机号
     */
//    @HystrixCommand
//    @ApiOperation(value = "通过账号查询手机号")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userName", value = "登入账户", dataType = "String", required = true)
//    })
//    @RequestMapping(value = "/findPhone", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
//    @ResponseBody
//    public ResponseEntity<ApiResult> findPhone(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
//        if (!StringUtils.validateParameter(usersVo.getUserName())) {
//            String message = "调用接口【/api/v1/user/findPhone时，参数userName不能为空";
//            log.warn(message);
//            ApiResult<Boolean> apiResult = new ApiResult<>();
//            apiResult.setSuccess(Boolean.FALSE);
//            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
//            apiResult.setMessage(message);
//            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
//        }
//        ServiceResult<User> serviceResult = userService.findPhone(usersVo);
//
//        ApiResult<User> apiResult = new ApiResult<>();
//        apiResult.setSuccess(serviceResult.getSuccess());
//        apiResult.setCode(HttpStatus.OK.value());
//        apiResult.setMessage(serviceResult.getMessage());
//        apiResult.setResult(serviceResult.getResult());
//        return new ResponseEntity<>(apiResult, HttpStatus.OK);
//    }

    /**
     * 忘记密码
     *
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", required = true),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "code", value = "短信验证码", dataType = "String", required = true)
    })
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> forgetPassword(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(usersVo.getPassword()) || !StringUtils.validateParameter(usersVo.getPhone()) || !StringUtils.validateParameter(usersVo.getCode())) {
            String message = "调用接口【/api/v1/user/forgetPassword时，参数password、phone、code不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        ServiceResult<Boolean> serviceResult = userService.forgetPassword(usersVo);
        if (serviceResult.getSuccess().equals(Boolean.FALSE)) {
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(serviceResult.getSuccess());
            apiResult.setCode(HttpStatus.UNAUTHORIZED.value());
            apiResult.setMessage(serviceResult.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.UNAUTHORIZED);
        }
        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);

    }

    /**
     * 新增账号
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "新增账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "登入账户", dataType = "String", required = true),
            @ApiImplicitParam(name = "position", value = "职位：1表示经理，2表示员工", dataType = "String", required = true),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "email", value = "电子邮箱", dataType = "String", required = true),
            @ApiImplicitParam(name = "roleListId", value = "角色相关信息", dataType = "List", required = true)
    })
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> save(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
        ApiResult<Boolean> apiResult;

        if (!StringUtils.validateParameter(usersVo.getUserName())
                || usersVo.getPosition() == null || usersVo.getPosition() == 0
                || !StringUtils.validateParameter(usersVo.getPhone()) || !StringUtils.validateParameter(usersVo.getEmail()) || usersVo.getRoleListId().size() == 0 || usersVo.getRoleListId() == null) {
            String message = "调用接口【/api/v1/user/save时，参数userName、position、phone、email、roleListId不能为空";
            log.warn(message);
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 判断当前账号是否重复
        ServiceResult<Boolean> userNameData = userService.findData(usersVo.getUserName(), UserType.USER_TYPE);
        if (userNameData.getSuccess().equals(Boolean.FALSE)) {
            apiResult = new ApiResult<>();
            apiResult.setSuccess(userNameData.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(userNameData.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        // 判断手机号是否重复
        ServiceResult<Boolean> phoneData = userService.findData(usersVo.getPhone(), UserType.PHONE_TYPE);
        if (phoneData.getSuccess().equals(Boolean.FALSE)) {
            apiResult = new ApiResult<>();
            apiResult.setSuccess(phoneData.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(phoneData.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        // 判断邮箱是否重复
        ServiceResult<Boolean> emailData = userService.findData(usersVo.getEmail(), UserType.EMAIL_TYPE);
        if (emailData.getSuccess().equals(Boolean.FALSE)) {
            apiResult = new ApiResult<>();
            apiResult.setSuccess(emailData.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(emailData.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        // 用户信息
        AuthenticationUser authenticationUser = this.getAuthenticationUser(request);
        if (null == authenticationUser) {
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(ApiResult.TOKEN_ILLEGAL_EXPIRE);
            return new ResponseEntity(apiResult, HttpStatus.UNAUTHORIZED);
        }

        //获取主账号id
        String id = authenticationUser.getId();
        ServiceResult<String> result = userService.saveUser(usersVo, id);
        //进行用户与角色关联
        roleService.saveUserToRole(usersVo.getRoleListId(), result.getResult(), id, usersVo.getPosition());

        if (result.getSuccess().equals(Boolean.FALSE)) {
            apiResult = new ApiResult<>();
            apiResult.setSuccess(result.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(result.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 当前主账号下分页展示子账号信息
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "当前主账号下分页展示子账号信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "String", required = true),
            @ApiImplicitParam(name = "pageNo", value = "当前页", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "显示几条", dataType = "Integer", required = true)
    })
    @RequestMapping(value = "/pageUser", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> pageUser(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
        if (usersVo.getPageSize() == null || usersVo.getPageNo() == null || !StringUtils.validateParameter(usersVo.getId())) {
            String message = "调用接口【/api/v1/user/pageUser时，参数pageSize、pageNo、id不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        //ServiceResult<List<User>> listServiceResult = userService.pageUser(usersVo);
        // 新的查询接口
        ServiceResult<PageNationPojo<UserPagePojo>> pageInfoServiceResult = userService.pageUserNew(usersVo);

        ApiResult<PageNationPojo<UserPagePojo>> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        apiResult.setResult(pageInfoServiceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 分页展示用户信息
     * 这个接口已不再使用
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
//    @HystrixCommand
//    @ApiOperation(value = "分页展示用户信息")
//    @ApiImplicitParam(name = "usersVo", value = "账号vo类", required = true, dataType = "UsersVo")
//    @RequestMapping(value = "/page", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
//    @ResponseBody
//    public ResponseEntity<ApiResult> page(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
//        if (usersVo.getPageSize() == null || usersVo.getPageNo() == null) {
//            String message = "调用接口【/api/v1/user/page时，参数pageSize、pageNo不能为空";
//            log.warn(message);
//            ApiResult<Boolean> apiResult = new ApiResult<>();
//            apiResult.setSuccess(Boolean.FALSE);
//            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
//            apiResult.setMessage(message);
//            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
//        }
//        ServiceResult<List<User>> listServiceResult = userService.findUserPage(usersVo);
//
//        ApiResult<List<User>> apiResult = new ApiResult<>();
//        apiResult.setSuccess(Boolean.TRUE);
//        apiResult.setCode(HttpStatus.OK.value());
//        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
//        apiResult.setResult(listServiceResult.getResult());
//        return new ResponseEntity<>(apiResult, HttpStatus.OK);
//    }

    @HystrixCommand
    @ApiOperation(value = "分页展示用户信息")
    @ApiImplicitParam(name = "usersVo", value = "账号vo类", required = true, dataType = "UsersVo")
    @RequestMapping(value = "/testRedis", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> testRedis(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
        ApiResult<List<User>> apiResult;
        if (usersVo.getPageSize() == null || usersVo.getPageNo() == null) {
            String message = "调用接口【/api/v1/user/page时，参数pageSize、pageNo不能为空";
            log.warn(message);
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        AuthenticationUser authenticationUser = this.getAuthenticationUser(request);
        if (null == authenticationUser) {
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(ApiResult.TOKEN_ILLEGAL_EXPIRE);
            return new ResponseEntity(apiResult, HttpStatus.UNAUTHORIZED);
        }

        ServiceResult<List<User>> listServiceResult = userService.page(authenticationUser.getId(),
                usersVo.getPageSize(), usersVo.getPageNo(), usersVo.getUserName(), usersVo.getRealName(),
                usersVo.getPosition(), usersVo.getPhone(), usersVo.getStatus());

        apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        apiResult.setResult(listServiceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 账号状态更改
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "账号状态更改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "账号id", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Integer", required = true)
    })
    @RequestMapping(value = "/modifyState", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> modifyState(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(usersVo.getId())
                || usersVo.getStatus() == null) {
            String message = "调用接口【/api/v1/users/modifyState时，参数id、status不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        userService.updateStatus(usersVo);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 重置密码
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "String", required = true)
    })
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> resetPassword(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.validateParameter(usersVo.getId())) {
            String message = "调用接口【/api/v1/users/resetPassword时，参数id不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        String header = request.getHeader(filterParamConfig.getToken());
        String[] headerArray = header.split(HttpHeader.TOKEN_SPLIT);
        if (null == headerArray || headerArray.length != 2) {
            String message = "调用接口【/api/v1/users/resetPassword时，参数token格式不对";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        } else {
            String token;
            token = headerArray[1];
            usersVo.setToken(token);
            ServiceResult<Boolean> serviceResult = userService.resetPassword(usersVo);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            if (serviceResult.getSuccess().equals(Boolean.FALSE)) {
                apiResult.setSuccess(serviceResult.getSuccess());
                apiResult.setCode(HttpStatus.UNAUTHORIZED.value());
                apiResult.setMessage(serviceResult.getMessage());
                return new ResponseEntity<>(apiResult, HttpStatus.UNAUTHORIZED);
            }
            apiResult.setSuccess(serviceResult.getSuccess());
            apiResult.setCode(HttpStatus.OK.value());
            apiResult.setMessage(serviceResult.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }
    }

    /**
     * 修改账号信息
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "修改账号信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "String", required = true),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "position", value = "职位：1表示经理，2表示员工", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "roleListId", value = "角色相关信息", dataType = "List", required = true)
    })
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> updateUser(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!StringUtils.validateParameter(usersVo.getId()) || !StringUtils.validateParameter(usersVo.getPhone()) || usersVo.getPosition() == null || usersVo.getRoleListId().size() == 0 || usersVo.getRoleListId() == null) {
            String message = "调用接口【/api/v1/users/updateUser时，参数id,phone,position,roleListId不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

//        // 判断手机号是否重复
//        ServiceResult<Boolean> phoneData = userService.findData(usersVo.getPhone(), UserType.PHONE_TYPE);
//        if (phoneData.getSuccess().equals(Boolean.FALSE)) {
//            ApiResult<Boolean> apiResult = new ApiResult<>();
//            apiResult = new ApiResult<>();
//            apiResult.setSuccess(phoneData.getSuccess());
//            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
//            apiResult.setMessage(phoneData.getMessage());
//            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
//        }
        // 用户信息
        AuthenticationUser authenticationUser = this.getAuthenticationUser(request);
        if (null == authenticationUser) {
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(ApiResult.TOKEN_ILLEGAL_EXPIRE);
            return new ResponseEntity(apiResult, HttpStatus.UNAUTHORIZED);
        }

        //获取主账号id
        String id = authenticationUser.getId();
        ServiceResult<Boolean> result = userService.updateUser(usersVo);
        //进行用户与角色关联
        roleService.saveUserToRole(usersVo.getRoleListId(), usersVo.getId(), authenticationUser.getId(), usersVo.getPosition());

        if (result.getSuccess().equals(Boolean.FALSE)) {
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(result.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(result.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 修改手机号
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "userName", value = "登入账户", dataType = "String", required = true)
    })
    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Map>> updatePhone(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!StringUtils.validateParameter(usersVo.getPhone())
                || !StringUtils.validateParameter(usersVo.getUserName())) {
            String message = "调用接口【/api/v1/users/updatePhone时，参数phone、userName不能为空";
            log.warn(message);
            ApiResult<Map> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        // 判断手机号是否重复
        ServiceResult<Boolean> phoneData = userService.findData(usersVo.getPhone(), UserType.PHONE_TYPE);
        if (phoneData.getSuccess().equals(Boolean.FALSE)) {
            ApiResult<Map> apiResult = new ApiResult<>();
            apiResult.setSuccess(phoneData.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(phoneData.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        ServiceResult<Map> result = userService.updatePhone(usersVo);

        if (result.getSuccess().equals(Boolean.FALSE)) {
            ApiResult<Map> apiResult = new ApiResult<>();
            apiResult.setSuccess(result.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(result.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        ApiResult<Map> apiResult = new ApiResult<>();
        apiResult.setResult(result.getResult());
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 修改密码
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码", dataType = "String", required = true)
    })
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> updatePassword(@RequestBody UsersVo usersVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!StringUtils.validateParameter(usersVo.getPassword())
                || !StringUtils.validateParameter(usersVo.getNewPassword())) {
            String message = "调用接口【/api/v1/users/updatePassword时，参数password、newPassword";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        String header = request.getHeader(filterParamConfig.getToken());
        String[] headerArray = header.split(HttpHeader.TOKEN_SPLIT);
        if (null == headerArray || headerArray.length != 2) {
            String message = "调用接口【/api/v1/users/updatePassword时，参数token格式不对";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        } else {
            String token;
            token = headerArray[1];
            usersVo.setToken(token);
            // 用户信息
            AuthenticationUser authenticationUser = this.getAuthenticationUser(request);//用于实现类中清缓存
            ServiceResult<Boolean> serviceResult = userService.updatePassword(usersVo, authenticationUser);
            if (serviceResult.getSuccess().equals(Boolean.FALSE)) {
                ApiResult<Boolean> apiResult = new ApiResult<>();
                apiResult.setSuccess(serviceResult.getSuccess());
                apiResult.setCode(HttpStatus.UNAUTHORIZED.value());
                apiResult.setMessage(serviceResult.getMessage());
                return new ResponseEntity<>(apiResult, HttpStatus.UNAUTHORIZED);
            }
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(serviceResult.getSuccess());
            apiResult.setCode(HttpStatus.OK.value());
            apiResult.setMessage(serviceResult.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }
    }

    /**
     * 用户登出
     *
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "用户登出")
    @ApiImplicitParam(name = "usersVo", value = "账号vo类", required = true, dataType = "usersVo")
    @RequestMapping(value = "/exit", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<Boolean>> exit(HttpServletRequest request, HttpServletResponse response) {
        this.removeAuthenticationUser(request);

        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.DELETE_SUCCESS);
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 用于erp定时任务查询子账号数据（erp那边暂时没用到此接口）
     *
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "用于erp定时任务查询子账号数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "日期时间", dataType = "Date", required = true),
            @ApiImplicitParam(name = "pageNo", value = "当前页", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "显示几条", dataType = "Integer", required = true)
    })
    @RequestMapping(value = "/sonUser", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> sonUser(HttpServletRequest request, HttpServletResponse response, @RequestBody UsersVo usersVo) {
        if (usersVo.getPageSize() == null || usersVo.getPageNo() == null || usersVo.getTime() == null) {
            String message = "调用接口【/api/v1/user/sonUser时，参数pageSize、pageNo、time不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<List<User>> listServiceResult = userService.allSonUserPage(usersVo.getPageNo(), usersVo.getPageSize(), usersVo.getTime());
        ApiResult<List<User>> apiResult = new ApiResult<>();
        apiResult.setSuccess(Boolean.TRUE);
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(ServiceResult.SELECT_SUCCESS);
        apiResult.setResult(listServiceResult.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 判断验证码是否正确
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "判断验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", required = true),
            @ApiImplicitParam(name = "code", value = "短信验证码", dataType = "String", required = true)
    })
    @RequestMapping(value = "/verificationCode", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> verificationCode(HttpServletRequest request, HttpServletResponse response, @RequestBody UsersVo usersVo) {
        if (!StringUtils.validateParameter(usersVo.getPhone()) || !StringUtils.validateParameter(usersVo.getCode())) {
            String message = "调用接口【/api/v1/user/verificationCode时，参数phone、code不能为空";
            log.warn(message);
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }
        ServiceResult<Boolean> codeData = userService.verificationCode(usersVo);//调用erp那边接口校验验证码是否正确
        if (codeData.getSuccess().equals(Boolean.FALSE)) {
            ApiResult<Boolean> apiResult = new ApiResult<>();
            apiResult.setSuccess(codeData.getSuccess());
            apiResult.setCode(apiResult.CODE_EXPIRE);
            apiResult.setMessage(codeData.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }
        ApiResult<Boolean> apiResult = new ApiResult<>();
        apiResult.setSuccess(codeData.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 通过主键获取当前用户详情
     *
     * @param usersVo
     * @param request
     * @param response
     * @return
     */
    @HystrixCommand
    @ApiOperation(value = "通过主键获取当前用户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", dataType = "String", required = true)
    })
    @RequestMapping(value = "/findUserData", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult<AuthenticationUser>> findUserData(HttpServletRequest request, HttpServletResponse response, @RequestBody UsersVo usersVo) {
        if (!StringUtils.validateParameter(usersVo.getId())) {
            String message = "调用接口【/api/v1/user/findUserData时，参数id不能为空";
            log.warn(message);
            ApiResult<AuthenticationUser> apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        ServiceResult<AuthenticationUser> userData = userService.queryUsers(usersVo.getId());//通过主键获取用户详情

        if (userData.getSuccess().equals(Boolean.FALSE)) {
            ApiResult<AuthenticationUser> apiResult = new ApiResult<>();
            apiResult.setSuccess(userData.getSuccess());
            apiResult.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            apiResult.setMessage(userData.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }
        ApiResult<AuthenticationUser> apiResult = new ApiResult<>();
        apiResult.setSuccess(userData.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setResult(userData.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}